<template>
  <div class="tabl-container">
    <el-table :data="paginatedPatients" style="width: 100%">
      <el-table-column fixed label="序号" width="100">
        <template #default="scope"> {{ (this.currentPage - 1) * this.pageSize + scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column fixed prop="name" label="患者姓名" width="150" />
      <el-table-column label="性别" width="150" >
        <template #default="scope">
          <span>{{ formatGender(scope.row.gender) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="250" />
      <el-table-column label="预约时间" width="250" >
        <template #default="scope">
          <span>{{ formatTime(scope.row.arrangeTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="150">
        <template #default="scope">
          <el-button :disabled="((this.currentPage - 1) * this.pageSize + scope.$index + 1) !== 1" type="primary" @click="handleCall(scope.$index, scope.row)">
            叫号
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-result v-if="!tableData.length" icon="info" title="当前时段无预约病人">
      <template #sub-title>
        <p>刷新查看是否有新增</p>
      </template>
    </el-result>
  </div>
  <div class="pagination-block">
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next"
      :total="tableData.length"
    />
  </div>
</template>

<script>
import request from "@/utils/request.js";

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 9,
      did: localStorage.getItem("dId"),
      // 原始数据
      tableData: [
        // {
        //   gender: "0",
        //   arrangeTime: "2025-01-04T09:11:08.000+00:00",
        //   name: "陈磊",
        //   arrangeid: "ARR90561",
        //   pid: "32716637",
        //   age: 28
        // },
        // {
        //   gender: "1",
        //   arrangeTime: "2025-01-04T09:21:34.000+00:00",
        //   name: "苏璐",
        //   arrangeid: "ARR56186",
        //   pid: "52757517",
        //   age: 43
        // },
      ]
   };
  },
  mounted() {
    this.requestQueue();
    console.log("当前页码:", this.currentPage);
  },
  computed: {
    paginatedPatients() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end);
    },
  },
  methods: {
    formatTime(timeString) {
      const date = new Date(timeString);
      const adjustedDate = new Date(date.getTime() - 8 * 60 * 60 * 1000); // 减去8小时（毫秒数）
      const year = adjustedDate.getFullYear();
      const month = String(adjustedDate.getMonth() + 1).padStart(2, '0');
      const day = String(adjustedDate.getDate()).padStart(2, '0');
      const hours = String(adjustedDate.getHours()).padStart(2, '0');
      const minutes = String(adjustedDate.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:00`;
    },
    formatTimeAndSubtractHours(timeString) {
      const date = new Date(timeString);
      const millisecondsInEightHours = 8 * 60 * 60 * 1000;
      const adjustedDate = new Date(date.getTime() - millisecondsInEightHours);
      return adjustedDate;
    },
    isWithinCurrentHour(dateToCheck) {
      // 获取当前时间
      const now = new Date();
      // 获取当前小时的开始时间（设置分钟、秒和毫秒为0）
      const currentHourStart = new Date(now);
      currentHourStart.setMinutes(0, 0, 0, 0);
      // 获取当前小时的结束时间（即下一个小时的开始时间减去1毫秒）
      const currentHourEnd = new Date(currentHourStart);
      currentHourEnd.setHours(currentHourStart.getHours() + 1, 0, 0, 0);
      currentHourEnd.setMilliseconds(currentHourEnd.getMilliseconds() - 1);
      // 检查dateToCheck是否在当前小时的时间段内
      return dateToCheck >= currentHourStart && dateToCheck < currentHourEnd;
    },
    requestQueue(){
      console.log("当前医生id", this.did);
      request
        .get(`/patient/getQueue?did=${this.did}`)
        .then((res) => {
          console.log('success',res);
          if(res.data) {
            this.tableData = res.data.filter(patient => {
              const adjustedTime = this.formatTimeAndSubtractHours(patient.arrangeTime);
              return this.isWithinCurrentHour(adjustedTime);
            });

          }
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    formatGender(gender) {
      return gender === 0 ? '女' : '男';
    },
    // 叫号
    handleCall(index, row) {
      console.log('叫号', row.name);
      request
      .get('/doctor/callPatient', {
          params: {
            dId: this.did,
            pId: row.pid
          }
        })
        .then((res) => {
          console.log('叫号成功,pid:',res,row.pid,"  arrangeid:",row.arrangeid);
          this.$message.success('叫号成功.');
          localStorage.setItem("currentArrangeId", row.arrangeid);
          // 从tableData中删除被叫号的患者数据
          this.tableData = this.tableData.filter(item => item.pid !== row.pid); 
          this.$router.push({ name: 'DoctorEditMedicalRecord', query: { patientName: row.name, patientIdCard: row.idCard } })
        })
        .catch((error) => {
            // 处理请求错误
            console.error('请求出错:', error);
        });
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      console.log("当前页码:", this.currentPage);
    },
  },
};
</script>

<style scoped>
/* 添加样式 */
.tabl-container {
  height: 65vh;
}
.pagination-block {
  display: flex; /* 使用flexbox布局 */
  justify-content: center; /* 水平居中对齐 */
  margin-top: 20px; /* 添加上边距 */
}
.pagination-block el-pagination {
  justify-content: center;
}
</style>